package com.nearbymap.model;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlResponse {

	private String responseXml;
	private Document responseDoc;
	XPath xpath = XPathFactory.newInstance().newXPath();
	
	public List<String> getTextAt(String xpathPattern) {
		List<String> list = new ArrayList<String>();
		try {
			NodeList nodes = getNodes(xpathPattern);
			for (int i = 0, n = nodes.getLength(); i < n; i++) {
				list.add(nodes.item(i).getTextContent());
			}
			return list;
		} catch (DOMException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public NodeList getNodes(String xpathPattern) {
		try {
			return (NodeList) xpath.evaluate(xpathPattern, this.responseDoc, XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (DOMException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public static Document loadXMLDocFromString(String xml) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputSource is = new InputSource(new StringReader(xml));
			return builder.parse(is);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (SAXException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public XmlResponse() {
	}

	public XmlResponse(String responseXml) {
		this.responseXml = responseXml;
		this.responseDoc = loadXMLDocFromString(responseXml);
	}

	public void setResponseXml(String responseXml) {
		this.responseXml = responseXml;
		this.responseDoc = loadXMLDocFromString(responseXml);
	}

	@Override
	public String toString() {
		return "XmlResponse [responseXml=" + responseXml + "]";
	}
	
}
